<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>S1手环数据解析工具</title>
    
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    
    <!-- Element Plus JS -->
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    
    <!-- Element Plus Icons -->
    <script src="https://unpkg.com/@element-plus/icons-vue/dist/index.iife.js"></script>
    
    <!-- Axios for HTTP requests -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    <script src="../js/menu-config.js"></script>
    <script src="../js/common-header.js"></script>
    <script src="../js/icons.js"></script>
    
    <!-- 引用外部样式表 -->
    <link rel="stylesheet" href="../css/global.css">
</head>
<body>
    <div id="app" class="layout-container">
        <div id="header-container"></div>
        
        <!-- 主体内容区 -->
        <div class="main-container">
            <!-- 左侧菜单栏 -->
            <aside class="sidebar" :class="{ collapsed: sidebarCollapsed, show: sidebarShow }">
                <div class="sidebar-content">
                    <ul class="nav-menu" id="nav-menu">
                        <!-- 菜单项将通过JavaScript动态生成 -->
                    </ul>
                </div>
            </aside>
            
            <!-- 右侧内容区 -->
            <main class="content-area">
                <!-- 面包屑导航 -->
                <div class="breadcrumb-container">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item><a href="../index.html">首页</a></el-breadcrumb-item>
                        <el-breadcrumb-item>S1手环数据解析</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                
                <!-- 页面标题 -->
                <div class="page-header">
                    <h1 class="page-title">S1手环数据解析</h1>
                    <p class="page-description">专业的S1手环原始数据解析工具，快速生成EDA和PPG数据文件</p>
                </div>
                
                <!-- 文件上传卡片 -->
                <div class="content-card">
                    <div class="card-header">
                        <h2>
                            <el-icon><Upload /></el-icon>
                            文件上传
                        </h2>
                    </div>
                    <div class="card-body">
                        <div 
                            class="upload-area"
                            :class="{ dragover: isDragOver }"
                            @drop="handleDrop"
                            @dragover="handleDragOver"
                            @dragleave="handleDragLeave"
                            @click="triggerFileInput"
                        >
                            <div class="upload-icon">
                                <el-icon><UploadFilled /></el-icon>
                            </div>
                            <div class="upload-text">点击或拖拽S1手环数据文件到此区域</div>
                            <div class="upload-hint">支持 .txt 格式的S1手环原始数据文件，单个文件最大100MB</div>
                        </div>
                        
                        <input 
                            ref="fileInput" 
                            type="file" 
                            multiple 
                            accept=".txt"
                            style="display: none;"
                            @change="handleFileSelect"
                        >
                        
                        <!-- 文件列表 -->
                        <div v-if="selectedFiles.length > 0" class="file-list">
                            <h4 style="margin-bottom: var(--spacing-md);">已选择文件 ({{ selectedFiles.length }})</h4>
                            <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
                                <div class="file-info">
                                    <el-icon color="var(--info-color)"><Document /></el-icon>
                                    <el-tooltip :content="file.name" placement="top" :disabled="file.name.length <= 25">
                                        <span class="file-name">{{ file.name }}</span>
                                    </el-tooltip>
                                    <span class="file-size">({{ formatFileSize(file.size) }})</span>
                                </div>
                                <el-button 
                                    type="danger" 
                                    size="small" 
                                    circle
                                    @click="removeFile(index)"
                                >
                                    <el-icon><Delete /></el-icon>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 解析选项卡片 -->
                <div class="content-card">
                    <div class="card-header">
                        <h2>
                            <el-icon><Setting /></el-icon>
                            数据解析配置
                        </h2>
                    </div>
                    <div class="card-body">
                        <div class="options-grid">
                            <div>
                                <el-checkbox v-model="includeTimestamp">包含时间戳</el-checkbox>
                                <div style="font-size: 12px; color: var(--text-secondary); margin-top: var(--spacing-xs);">
                                    在输出的EDA和PPG数据文件中包含原始时间戳信息
                                </div>
                            </div>
                            
                            <div>
                                <label style="display: block; margin-bottom: var(--spacing-sm); font-weight: 500;">输出格式：</label>
                                <el-checkbox-group v-model="outputFormats">
                                    <el-checkbox label="csv">CSV格式</el-checkbox>
                                    <el-checkbox label="json">JSON格式</el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </div>
                        
                        <div style="margin-top: var(--spacing-xl); text-align: center;">
                            <el-button 
                                type="primary" 
                                size="large"
                                :disabled="selectedFiles.length === 0 || isProcessing"
                                :loading="isUploading"
                                @click="startProcessing"
                            >
                                <el-icon v-if="!isUploading"><Upload /></el-icon>
                                {{ isUploading ? '解析中...' : '开始解析数据' }}
                            </el-button>
                        </div>
                    </div>
                </div>
                
                <!-- 解析结果卡片 -->
                <div v-if="parseResults.length > 0" class="content-card">
                    <div class="card-header">
                        <h2>
                            <el-icon><SuccessFilled /></el-icon>
                            数据解析结果
                        </h2>
                    </div>
                    <div class="card-body">
                        <div v-for="result in parseResults" :key="result.task_id" class="result-item">
                            <div class="result-header">
                                <div style="display: flex; align-items: center;">
                                    <strong>{{ result.filename }}</strong>
                                    <span class="status-badge status-success" style="margin-left: var(--spacing-sm);">
                                        <el-icon style="margin-right: var(--spacing-xs);"><Check /></el-icon>
                                        解析完成
                                    </span>
                                </div>
                                <el-button 
                                    type="primary" 
                                    size="small"
                                    @click="downloadAllFiles(result.task_id)"
                                >
                                    <el-icon style="margin-right: var(--spacing-xs);"><Download /></el-icon>
                                    下载全部
                                </el-button>
                            </div>
                            
                            <div class="result-files">
                                <div v-for="output in result.outputs" :key="output.filename" style="display: flex; justify-content: space-between; align-items: center; padding: var(--spacing-sm) 0; border-bottom: 1px solid var(--border-color);">
                                    <div style="display: flex; align-items: center;">
                                        <el-icon color="var(--success-color)" style="margin-right: var(--spacing-xs);"><Document /></el-icon>
                                        <span>{{ output.filename }}</span>
                                        <el-tag size="small" style="margin-left: var(--spacing-sm);">{{ output.type }}</el-tag>
                                    </div>
                                    <el-button 
                                        type="text" 
                                        size="small"
                                        @click="downloadSingleFile(result.task_id, output.filename)"
                                    >
                                        <el-icon><Download /></el-icon>
                                    </el-button>
                                </div>
                            </div>
                        </div>
                        
                        <div style="text-align: center; margin-top: var(--spacing-lg);">
                            <el-button 
                                type="success" 
                                size="large"
                                @click="downloadAllResults"
                            >
                                <el-icon style="margin-right: var(--spacing-xs);"><Download /></el-icon>
                                下载所有结果 (ZIP)
                            </el-button>
                        </div>
                    </div>
                </div>
                
                <!-- 错误信息 -->
                <div v-if="errors.length > 0" style="margin-top: var(--spacing-lg);">
                    <el-alert
                        v-for="(error, index) in errors"
                        :key="index"
                        :title="error"
                        type="error"
                        style="margin-bottom: var(--spacing-sm);"
                        show-icon
                        closable
                    />
                </div>
            </main>
        </div>
        
        <!-- 加载遮罩 -->
        <div v-if="isProcessing" class="loading-overlay">
            <div class="loading-content">
                <el-icon class="is-loading" style="font-size: 32px; color: var(--info-color); margin-bottom: var(--spacing-lg);">
                    <Loading />
                </el-icon>
                <div style="font-size: 16px; margin-bottom: var(--spacing-sm);">{{ loadingText }}</div>
                                <div style="font-size: 14px; color: var(--text-secondary);">正在处理您的S1手环数据文件，请稍候...</div>
            </div>
        </div>
    </div>

    <script>
        const { createApp } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;
        
        const app = createApp({
            data() {
                return {
                    sidebarCollapsed: false,
                    sidebarShow: false,
                    
                    // 文件上传相关
                    selectedFiles: [],
                    isDragOver: false,
                    includeTimestamp: false,
                    outputFormats: ['csv'],
                    isUploading: false,
                    isProcessing: false,
                    loadingText: '正在上传文件...',
                    parseResults: [],
                    errors: [],
                    currentTaskId: null
                }
            },
            computed: {
                // 使用统一的图标配置
                ...window.IconsConfig.getIconsComputed()
            },
            methods: {
                toggleSidebar() {
                    if (window.innerWidth <= 575) {
                        this.sidebarShow = !this.sidebarShow;
                    } else {
                        this.sidebarCollapsed = !this.sidebarCollapsed;
                    }
                },
                
                goHome() {
                    window.location.href = '../index.html';
                },
                
                // 文件处理方法
                triggerFileInput() {
                    this.$refs.fileInput.click();
                },
                
                handleFileSelect(event) {
                    const files = Array.from(event.target.files);
                    this.addFiles(files);
                    event.target.value = '';
                },
                
                handleDrop(event) {
                    event.preventDefault();
                    this.isDragOver = false;
                    const files = Array.from(event.dataTransfer.files);
                    this.addFiles(files);
                },
                
                handleDragOver(event) {
                    event.preventDefault();
                    this.isDragOver = true;
                },
                
                handleDragLeave(event) {
                    event.preventDefault();
                    this.isDragOver = false;
                },
                
                addFiles(files) {
                    const txtFiles = files.filter(file => file.name.toLowerCase().endsWith('.txt'));
                    
                    if (txtFiles.length !== files.length) {
                        ElMessage.warning('只支持.txt格式的文件，其他格式文件已被过滤');
                    }
                    
                    txtFiles.forEach(file => {
                        if (file.size > 100 * 1024 * 1024) {
                            ElMessage.error(`文件 ${file.name} 超过100MB限制`);
                            return;
                        }
                        
                        const exists = this.selectedFiles.some(f => f.name === file.name && f.size === file.size);
                        if (!exists) {
                            this.selectedFiles.push(file);
                        }
                    });
                    
                    if (txtFiles.length > 0) {
                        ElMessage.success(`成功添加 ${txtFiles.length} 个文件`);
                    }
                },
                
                removeFile(index) {
                    this.selectedFiles.splice(index, 1);
                },
                
                formatFileSize(bytes) {
                    if (bytes === 0) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                },
                
                // 文件处理和上传方法
                async startProcessing() {
                    if (this.selectedFiles.length === 0) {
                        ElMessage.warning('请先选择要处理的文件');
                        return;
                    }
                    
                    if (this.outputFormats.length === 0) {
                        ElMessage.warning('请至少选择一种输出格式');
                        return;
                    }
                    
                    this.isUploading = true;
                    this.isProcessing = true;
                    this.loadingText = '正在上传文件...';
                            this.errors = [];
                            
                            try {
                                const formData = new FormData();
                                this.selectedFiles.forEach(file => {
                                    formData.append('files', file);
                                });
                                formData.append('include_timestamp', this.includeTimestamp);
                                formData.append('output_formats', JSON.stringify(this.outputFormats));
                                
                                this.loadingText = '正在解析S1手环数据...';
                                
                                const response = await axios.post('/api/files/convert', formData, {
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    },
                                    timeout: 300000 // 5分钟超时
                                });
                                
                                if (response.data.success) {
                                    // 为每个结果添加task_id字段
                                    this.parseResults = response.data.results.map(result => ({
                                        ...result,
                                        task_id: response.data.task_id
                                    }));
                                    this.currentTaskId = response.data.task_id;
                                    ElMessage.success('S1手环数据解析完成！');
                                    
                                    // 清空已选择的文件
                                    this.selectedFiles = [];
                                } else {
                                    throw new Error(response.data.message || '数据解析失败');
                                }
                            } catch (error) {
                                console.error('数据解析失败:', error);
                                this.errors.push(error.response?.data?.message || error.message || '数据解析过程中发生错误');
                                ElMessage.error('S1手环数据解析失败，请检查文件格式或稍后重试');
                            } finally {
                                this.isUploading = false;
                                this.isProcessing = false;
                            }
                },
                
                // 下载方法
                async downloadSingleFile(taskId, filename) {
                    try {
                        const response = await axios.get(`/api/files/download/${taskId}/${filename}`, {
                            responseType: 'blob'
                        });
                        
                        const url = window.URL.createObjectURL(new Blob([response.data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', filename);
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                        window.URL.revokeObjectURL(url);
                        
                        ElMessage.success('文件下载成功');
                    } catch (error) {
                        console.error('下载失败:', error);
                        ElMessage.error('文件下载失败');
                    }
                },
                
                async downloadAllFiles(taskId) {
                    try {
                        const response = await axios.get(`/api/files/download/${taskId}`, {
                            responseType: 'blob'
                        });
                        
                        const url = window.URL.createObjectURL(new Blob([response.data]));
                        const link = document.createElement('a');
                        link.href = url;
                        link.setAttribute('download', `${taskId}_results.zip`);
                        document.body.appendChild(link);
                        link.click();
                        link.remove();
                        window.URL.revokeObjectURL(url);
                        
                        ElMessage.success('文件下载成功');
                    } catch (error) {
                        console.error('下载失败:', error);
                        ElMessage.error('文件下载失败');
                    }
                },
                
                async downloadAllResults() {
                    if (this.parseResults.length === 0 || !this.currentTaskId) {
                        ElMessage.warning('没有可下载的结果');
                        return;
                    }
                    try {
                        await this.downloadAllFiles(this.currentTaskId);
                    } catch (error) {
                        console.error('下载失败:', error);
                        ElMessage.error('文件下载失败');
                    }
                }
            },
            mounted() {
                // 初始化页面菜单和标题
                const pageName = 'data-parse.html';
                if (window.MenuConfig) {
                    window.MenuConfig.initializePageMenu(pageName);
                } else if (typeof initializePageMenu === 'function') {
                    initializePageMenu(pageName);
                }
                
                // 初始化通用header
                window.CommonHeader.initHeader('header-container');
                
                // 监听窗口大小变化
                window.addEventListener('resize', () => {
                    if (window.innerWidth > 575) {
                        this.sidebarShow = false;
                    }
                });
            }
        });
        
        // 注册图标并挂载应用
        window.IconsConfig.registerIcons(app);
        app.use(ElementPlus).mount('#app');
    </script>
</body>
</html>